<template>
	<div class="inHospital_box">
		<!-- 新增房间按钮和返回按钮 -->
		<div class="addRoom_box">
			<el-button v-if="isCheckRoomView || isSettlementView" type="primary" class="mt10 mr30" style="border-radius: 10px" @click="goBack">
				返回
			</el-button>
			<div v-else style="flex: 1"></div>
			<el-button type="primary" class="mt10 mr30" style="border-radius: 10px" @click="handleAdd"> 新增房间 </el-button>
		</div>

		<!-- 房间列表视图 -->
		<template v-if="!isCheckRoomView && !isSettlementView">
			<div class="room_box">
				<div class="room_title">房间管理</div>
				<!-- 房间搜索部分 -->
				<div class="room_search">
					<!-- 状态选择 -->
					<el-select 
						v-model="statusValue" 
						class="m-2" 
						placeholder="请选择状态" 
						style="width: 240px; margin-left: 15px"
						clearable
						@change="handleSearch"
					>
						<el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>

					<!-- 房间号 -->
					<el-input 
						v-model="roomNumber" 
						placeholder="输入房间号" 
						clearable 
						@input="formatRoomNumberInput" 
						@blur="handleSearch"
						style="width: 20%; margin-left: 15px" 
					/>
					<!-- 床号 -->
					<el-input 
						v-model="bedNumber" 
						placeholder="输入床号" 
						clearable 
						@input="formatBedNumberInput" 
						@blur="handleSearch"
						style="width: 20%; margin-left: 15px" 
					/>
					<!-- 科室 -->
					<el-select
						v-model="departmentValue"
						class="m-2"
						placeholder="请选择科室"
						style="width: 240px; margin-left: 15px"
						:loading="departmentLoading"
						clearable
						@change="handleSearch"
					>
						<el-option v-for="item in departmentOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</div>

				<!-- 列表部分 -->
				<div class="room_list">
					<!-- 房间列表项 -->
					<div class="room_list_item_wrapper" v-for="item in paginatedRoomData" :key="item.id">
						<!-- 图片区域 -->
						<div class="room_list_item">
							<el-image
								:src="getImageUrl(item.img)"
								:alt="item.room_num"
								style="width: 70px; height: 50px"
								fit="cover"
								:preview-src-list="[getImageUrl(item.img)]"
								preview-teleported
							>
								<template #error>
									<div class="image-error">
										<el-icon>
											<Picture />
										</el-icon>
									</div>
								</template>
							</el-image>
						</div>
						<!-- 房间信息 -->
						<div class="room_list_itemText">
							<div class="room_list_item_info">
								<div class="item_roomNum">{{ item.room_num }}</div>
								<div class="room_list_item_info_office">{{ item.detart_name || getDepartmentName(item.department) }}</div>
								<div class="room_list_item_bedNum">{{ item.bed_num }}</div>
							</div>
							<div class="room_list_item_state">
								<div class="room_list_item_state_text" :class="getStatusClass(item.room_status)">
									{{ getStatusText(item.room_status) }}
								</div>
							</div>
							<div class="room_list_item_time">
								<div class="room_list_item_time_text">{{ item.create_time }}</div>
							</div>
						</div>
						<!-- 功能按钮 -->
						<div class="room_list_item_function">
							<el-button size="small" type="primary" plain @click="handleCheckRoom(item, item.card)" :disabled="item.room_status === 1">
								查房
							</el-button>
							<el-button size="small" type="primary" plain @click="handleSettle(item, item.card)" :disabled="item.room_status === 1">
								结算
							</el-button>
							<el-button size="small" type="primary" plain @click="handleAdmit(item)" :disabled="item.room_status === 2"> 住院 </el-button>
						</div>
					</div>
				</div>

				<!-- 分页 -->
				<div class="pagination-container">
					<el-pagination
						@current-change="handleCurrentChange"
						:current-page="currentPage"
						:page-size="pageSize"
						:total="filteredRoomData.length"
						layout="prev, pager, next, jumper"
						background
					/>
				</div>
			</div>
		</template>

		<!-- 查房视图 -->
		<template v-if="isCheckRoomView && !isSettlementView">
			<div class="check-room-container">
				<!-- 顶部标题 -->
				<div class="check-header">
					<h2 class="check-title">患者信息</h2>
				</div>

				<!-- 患者信息 - 头像在右侧 -->
				<div class="patient-info">
					<div class="patient-details">
						<div class="detail-item"><span class="label">姓名：</span>{{ patientCardInfo.nickname || '未知' }}</div>
						<div class="detail-item">
							<span class="label">性别：</span>{{ patientCardInfo.sex === 1 ? '男' : patientCardInfo.sex === 2 ? '女' : '未知' }}
						</div>
						<div class="detail-item" style="display: flex">
							<span class="label">账户头像：</span>
							<div class="patient-avatar">
								<el-image
									:src="getPatientAvatar()"
									alt="患者头像"
									fit="cover"
									style="width: 60px; height: 60px; border-radius: 50%"
									:preview-src-list="[getPatientAvatar()]"
									preview-teleported
								>
									<template #error>
										<div class="image-error">
											<el-icon>
												<User />
											</el-icon>
										</div>
									</template>
								</el-image>
							</div>
						</div>
						<div class="detail-item"><span class="label">证件类型：</span>身份证</div>
						<div class="detail-item"><span class="label">身份证号：</span>{{ patientCardInfo.code || '未知' }}</div>
						<div class="detail-item"></div>
						<div class="detail-item"><span class="label">就诊人地址：</span>{{ patientCardInfo.address || '未知' }}</div>
						<div class="detail-item"><span class="label">手机号：</span>{{ patientCardInfo.tel || '未知' }}</div>
						<div class="detail-item"><span class="label">关系：</span>{{ getRelationText(patientCardInfo.relationship) }}</div>
					</div>
				</div>

				<!-- 顶部标题 -->
				<div class="check-header">
					<h2 class="check-title">查房记录</h2>
				</div>
				<!-- 查房记录区域 -->
				<div class="check-record">
					<!-- 左侧时间线 -->
					<div class="timeline-container">
						<el-timeline v-if="checkRecords && checkRecords.length > 0">
							<el-timeline-item
								v-for="(record, index) in checkRecords"
								:key="record.id || index"
								:timestamp="formatDate(record.check_time)"
								:placement="'bottom'"
								:class="{ 'active-timeline': activeRecordId === (record.id || index) }"
								@click="selectRecord(record, index)"
							>
								<div class="timeline-content">
									{{ getTimelineLabel(record) }}
								</div>
							</el-timeline-item>
						</el-timeline>
						<div v-else class="no-records">暂无查房记录</div>
					</div>


					<!-- 右侧相关信息 - 按新布局组织 -->
					<div class="check-form">
						<el-form ref="checkFormRef" :model="checkForm" :rules="checkRules" label-width="0">
							<!-- 第一行：房间号，住院状态和科室 -->
							<div class="form-row">
								<div class="form-group">
									<span class="form-label">房间号：</span>
									<span class="form-value">{{ currentRoom.room_num || '未知' }}</span>
								</div>
								<div class="form-group">
									<span class="form-label">住院状态：</span>
									<span class="form-value">{{
										patientCardInfo.hospital_status == 1 ? '欠费' : patientCardInfo.hospital_status == 2 ? '住院中' : '未知'
									}}</span>
								</div>
								<div class="form-group">
									<span class="form-label">科室：</span>
									<span class="form-value">{{ getDepartmentName(currentRoom.depart_id) }}</span>
								</div>
							</div>

							<!-- 第二行：住院原因和查房次数 -->
							<div class="form-row">
								<div class="form-group">
									<span class="form-label">住院原因：</span>
									<span class="form-value">{{ currentRoom.hospital_reason || '无' }}</span>
								</div>
								<div class="form-group">
									<span class="form-label">查房次数：</span>
									<el-form-item prop="day">
										<el-input v-model.number="checkForm.day" placeholder="查房次数" readonly style="width: 120px" />
									</el-form-item>
								</div>
							</div>

							<!-- 第三行：查房日期和查房医生 -->
							<div class="form-row">
								<div class="form-group">
									<span class="form-label">查房日期：</span>
									<el-form-item prop="check_time">
										<el-date-picker
											v-model="checkForm.check_time"
											type="date"
											placeholder="选择查房时间"
											value-format="YYYY-MM-DD"
											style="width: 180px"
											readonly
										/>
									</el-form-item>
								</div>
								<div class="form-group">
									<span class="form-label">查房医生：</span>
									<el-form-item prop="name">
										<el-input v-model="checkForm.name" placeholder="请输入查房医生姓名" style="width: 180px" @input="handleNameChange" />
									</el-form-item>
								</div>
							</div>

							<!-- 第四行：查房情况 -->
							<div class="form-row">
								<div class="form-group full-width">
									<span class="form-label">查房情况：</span>
									<el-form-item prop="situation">
										<el-input v-model="checkForm.situation" placeholder="请输入查房情况" style="flex: 1" @input="handleSituationChange" />
									</el-form-item>
								</div>
							</div>

							<!-- 第五行：体温，呼吸，心率，血压 -->
							<div class="form-row">
								<div class="form-group">
									<span class="form-label">体温 (°C)：</span>
									<el-form-item prop="temperature">
										<el-input
											v-model.number="checkForm.temperature"
											placeholder="体温"
											type="number"
											step="0.1"
											min="35"
											max="42"
											style="width: 100px"
											@blur="handleTemperatureBlur"
										/>
									</el-form-item>
								</div>
								<div class="form-group">
									<span class="form-label">呼吸 (次/分)：</span>
									<el-form-item prop="breathe">
										<el-input
											v-model.number="checkForm.breathe"
											placeholder="12-20"
											type="number"
											min="12"
											max="20"
											style="width: 100px"
											@blur="handleBreatheBlur"
										/>
									</el-form-item>
								</div>
								<div class="form-group">
									<span class="form-label">心率 (次/分)：</span>
									<el-form-item prop="rate">
										<el-input
											v-model.number="checkForm.rate"
											placeholder="60-100"
											type="number"
											min="60"
											max="100"
											style="width: 100px"
											@blur="handleRateBlur"
										/>
									</el-form-item>
								</div>
								<div class="form-group">
									<span class="form-label">血压 (mmHg)：</span>
									<el-form-item prop="blood">
										<el-input
											v-model="checkForm.blood"
											placeholder="如: 120/80"
											style="width: 120px"
											@blur="handleBloodBlur"
											@input="formatBloodInput"
										/>
									</el-form-item>
								</div>
							</div>

							<!-- 第六行：查房备注 -->
							<div class="form-row">
								<div class="form-group full-width">
									<span class="form-label">查房备注：</span>
									<el-form-item prop="note">
										<el-input
											v-model="checkForm.note"
											placeholder="请输入查房备注"
											type="textarea"
											:rows="4"
											:maxlength="200"
											show-word-limit
											style="flex: 1"
											@input="handleNoteChange"
										/>
									</el-form-item>
								</div>
							</div>
						</el-form>
					</div>
				</div>

				<!-- 底部按钮 -->
				<div class="check-buttons">
					<el-button @click="resetForm">重置</el-button>
					<el-button type="primary" @click="restoreForm">恢复</el-button>
					<el-button type="success" @click="saveCheckRecord">保存</el-button>
				</div>
			</div>
		</template>

		<!-- 结算管理视图 -->
		<template v-if="isSettlementView">
			<div class="settlement-container">
				<div class="settlement-content">
					<!-- 患者信息区域 -->
					<div class="check-header">
						<h2 class="check-title">患者信息</h2>
					</div>

					<div class="patient-info" v-if="patientLoading">
						<el-skeleton :rows="8" :cols="4" active />
					</div>

					<div class="patient-info" v-else>
						<div class="patient-details">
							<div class="detail-item"><span class="label">姓名：</span>{{ settlementPatientInfo.nickname || '未知' }}</div>
							<div class="detail-item"><span class="label">医生姓名：</span>{{ doctorName || '暂无' }}</div>
							<div class="detail-item" style="display: flex">
								<span class="label">患者头像：</span>
								<div class="patient-avatar">
									<el-image
										:src="getSettlementPatientAvatar()"
										alt="患者头像"
										fit="cover"
										style="width: 60px; height: 60px; border-radius: 50%"
										:preview-src-list="[getSettlementPatientAvatar()]"
										preview-teleported
									>
										<template #error>
											<div class="image-error">
												<el-icon>
													<User />
												</el-icon>
											</div>
										</template>
									</el-image>
								</div>
							</div>
							<div class="detail-item"><span class="label">证件类型：</span>身份证</div>
							<div class="detail-item"><span class="label">证件号码：</span>{{ settlementPatientInfo.code || '未知' }}</div>
							<div class="detail-item"></div>
							<div class="detail-item"><span class="label">地址：</span>{{ settlementPatientInfo.address || '未知' }}</div>
							<div class="detail-item"><span class="label">联系电话：</span>{{ settlementPatientInfo.tel || '未知' }}</div>
							<div class="detail-item"><span class="label">关系：</span>{{ getRelationText(settlementPatientInfo.relationship) }}</div>

							<div class="detail-item">
								<span class="label">性别：</span>{{ settlementPatientInfo.sex === 1 ? '男' : settlementPatientInfo.sex === 2 ? '女' : '未知' }}
							</div>
							<div class="detail-item"><span class="label">就诊时间：</span>{{ settlementPatientInfo.create_time || '未知' }}</div>
						</div>
					</div>

					<!-- 费用明细区域 -->
					<div class="check-header">
						<h2 class="check-title">费用明细</h2>
					</div>

					<!-- 按钮行 -->
					<div class="settlement-actions">
						<el-button type="primary" @click="openAddServiceDialog">新增服务</el-button>

						<!-- 就诊完成选项 -->
						<el-popover v-model:visible="showCompleteOptions" placement="bottom" width="200" trigger="click">
							<div class="complete-options">
								<div class="option-item" @click="handleCompleteWithExam">有体检项目</div>
								<div class="option-item" @click="handleCompleteWithoutExam">没有体检项目</div>
							</div>
							<template #reference>
								<el-button type="success">就诊完成</el-button>
							</template>
						</el-popover>
					</div>

					<!-- 费用表格 -->
					<div class="settlement-table" v-if="settlementLoading">
						<el-skeleton :rows="5" active />
					</div>

					<div class="settlement-table" v-else>
						<el-table :data="paginatedSettlements" border style="width: 100%">
							<el-table-column type="index" label="序号" width="80" />
							<el-table-column prop="service_name" label="服务名称" />
							<el-table-column prop="service_type" label="服务类型">
								<template #default="scope">
									{{ scope.row.service_type == 1 ? '药品' : scope.row.service_type == 0 ? '体检' : '未知' }}
								</template>
							</el-table-column>
							<el-table-column prop="specification" label="单价（元）">
								<template #default="scope">
									<span v-if="scope.row.specification !== undefined && scope.row.specification !== null">
										¥{{ parseFloat(scope.row.specification).toFixed(2) }}
									</span>
									<span v-else>-</span>
								</template>
							</el-table-column>
							<el-table-column prop="specifi" label="规格" />
							<el-table-column prop="subtotal" label="小计（元）">
								<template #default="scope">
									<span v-if="scope.row.subtotal !== undefined && scope.row.subtotal !== null">
										¥{{ parseFloat(scope.row.subtotal).toFixed(2) }}
									</span>
									<span v-else>-</span>
								</template>
							</el-table-column>
							<el-table-column prop="status" label="订单状态">
								<template #default="scope">
									<el-tag :type="getStatusTagType(scope.row.status)">
										{{ getSettlementStatusText(scope.row.status) }}
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="120">
								<template #default="scope">
									<el-button type="danger" plain size="small" @click="handleDelete(scope.row.id, scope.$index)"> 删除 </el-button>
								</template>
							</el-table-column>
						</el-table>

						<!-- 无数据提示 -->
						<div v-if="settlementData.length === 0" class="no-records">暂无费用记录</div>

						<!-- 分页 -->
						<div class="pagination-container" v-if="settlementData.length > 0">
							<el-pagination
								@current-change="handleSettlementPageChange"
								:current-page="settlementCurrentPage"
								:page-size="settlementPageSize"
								:total="settlementData.length"
								layout="prev, pager, next, jumper"
								background
							/>
						</div>
					</div>
				</div>

				<!-- 新增服务弹窗 -->
				<el-dialog v-model="addServiceVisible" title="新增服务" width="50%">
					<el-form ref="serviceFormRef" :model="serviceForm" :rules="serviceRules" label-width="100px">
						<el-form-item label="服务类型" prop="service_type">
							<el-select v-model="serviceForm.service_type" placeholder="请选择服务类型" @change="handleServiceTypeChange">
								<el-option label="体检" value="1" />
								<el-option label="药品" value="2" />
							</el-select>
						</el-form-item>

						<el-form-item label="服务名称" prop="service_id">
							<el-select
								v-model="serviceForm.service_id"
								placeholder="请选择服务名称"
								:disabled="!serviceForm.service_type"
								:loading="packageLoading || drugLoading"
								@change="handleServiceChange"
							>
								<el-option
									v-for="item in filteredServiceOptions"
									:key="item.id"
									:label="item.name + ' (¥' + (item.price || 0) + ')'"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>

						<el-form-item label="数量" prop="specification">
							<el-input-number v-model="serviceForm.specification" :min="1" :step="1" step-strictly @change="calculateSubtotal" />
						</el-form-item>

						<el-form-item label="单价（元）" prop="price">
							<el-input v-model.number="serviceForm.price" placeholder="自动填充" disabled />
						</el-form-item>

						<el-form-item label="小计（元）" prop="subtotal">
							<el-input v-model.number="serviceForm.subtotal" placeholder="自动计算" disabled />
						</el-form-item>
					</el-form>

					<template #footer>
						<div class="dialog-footer">
							<el-button @click="cancelAddService">取消</el-button>
							<el-button type="primary" @click="confirmAddService">确认</el-button>
						</div>
					</template>
				</el-dialog>

				<!-- 体检结果上传弹窗 -->
				<el-dialog v-model="uploadExamVisible" title="上传体检结果" width="50%">
					<el-form ref="examFormRef" :model="examForm" :rules="examRules" label-width="100px">
						<el-form-item label="体检名称" prop="name">
							<el-input v-model="examForm.name" placeholder="请输入体检名称" />
						</el-form-item>

						<el-form-item label="体检结果" prop="result">
							<el-input v-model="examForm.result" placeholder="请输入体检结果" type="textarea" rows="3" />
						</el-form-item>

						<el-form-item label="上传报告" prop="file">
							<el-upload
								ref="uploadRef"
								action=""
								list-type="text"
								:auto-upload="false"
								:limit="1"
								:on-change="handleExamFileChange"
								:on-remove="handleExamFileRemove"
								:file-list="examFileList"
								:accept="'.pdf,.jpg,.jpeg,.png,.gif'"
							>
								<el-button type="primary">选择文件</el-button>
								<template #tip>
									<div class="el-upload__tip">请上传PDF或图片格式的体检报告（最大支持{{ maxFileSize / 1024 / 1024 }}MB）</div>
								</template>
							</el-upload>
							<!-- 显示文件大小信息 -->
							<div v-if="examFileList.length > 0" class="file-info">
								文件名: {{ examFileList[0].name }} 文件大小: {{ formatFileSize(examFileList[0].size) }}
							</div>
						</el-form-item>
					</el-form>

					<template #footer>
						<el-button @click="cancelUploadExam">取消</el-button>
						<el-button type="primary" @click="confirmUploadExam">确定</el-button>
					</template>
				</el-dialog>

				<!-- 头像预览弹窗 -->
				<el-dialog v-model="avatarPreviewVisible" title="患者头像" width="300px">
					<el-image
						:src="getPatientAvatar()"
						alt="患者头像"
						style="width: 100%; height: auto"
						fit="cover"
						:preview-src-list="[getPatientAvatar()]"
						preview-teleported
					>
						<template #error>
							<div class="image-error">
								<el-icon>
									<User />
								</el-icon>
							</div>
						</template>
					</el-image>
				</el-dialog>

				<!-- 结算页面头像预览弹窗 -->
				<el-dialog v-model="settlementAvatarPreviewVisible" title="患者头像" width="300px">
					<el-image
						:src="getSettlementPatientAvatar()"
						alt="患者头像"
						style="width: 100%; height: auto"
						fit="cover"
						:preview-src-list="[getSettlementPatientAvatar()]"
						preview-teleported
					>
						<template #error>
							<div class="image-error">
								<el-icon>
									<User />
								</el-icon>
							</div>
						</template>
					</el-image>
				</el-dialog>
			</div>
		</template>

		<!-- 新增房间弹窗 -->
		<el-dialog v-model="dialogFormVisible" title="新增房间" width="600px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="科室" prop="department">
					<el-cascader
						v-model="form.department"
						:options="departmentOptions"
						:props="cascaderProps"
						:show-all-levels="false"
						placeholder="请选择科室"
						clearable
						style="width: 100%"
						:loading="departmentLoading"
					/>
				</el-form-item>
				<el-form-item label="房间号" prop="room_num">
					<el-input v-model="form.room_num" placeholder="请输入房间号" @input="formatRoomInput" />
				</el-form-item>
				<el-form-item label="床号" prop="bed_num">
					<el-input v-model="form.bed_num" placeholder="请输入床号" @input="formatBedInput" />
				</el-form-item>
				<el-form-item label="图片" prop="img">
					<div class="avatar_uploader">
						<el-upload
							ref="uploadRef"
							list-type="picture-card"
							:auto-upload="false"
							:limit="1"
							:on-change="handleUpload"
							:on-remove="handleRemove"
							:file-list="fileList"
							:class="{ 'hide-upload': fileList.length > 0 }"
							accept="image/jpeg, image/png"
						>
							<template v-if="fileList.length === 0">
								<el-icon>
									<Plus />
								</el-icon>
							</template>
							<template v-else>
								<el-image
									:src="fileList[0].url"
									style="width: 100%; height: 100%"
									fit="cover"
									:preview-src-list="[fileList[0].url]"
									preview-teleported
								/>
							</template>
						</el-upload>
						<!-- 显示文件大小信息 -->
						<div v-if="fileList.length > 0" class="file-info">
							文件大小: {{ formatFileSize(fileList[0].size) }}
							<span class="file-limit">（最大支持{{ maxFileSize / 1024 / 1024 }}MB）</span>
						</div>
						<div class="upload-hint">支持 JPG/PNG 格式，大小不超过 2MB</div>
					</div>
				</el-form-item>
				<el-form-item label="就诊卡号" prop="card">
					<el-select
						v-model="form.card"
						placeholder="请选择就诊卡号"
						size="default"
						clearable
						filterable
						:loading="cardLoading"
						@visible-change="handleCardSelectVisibleChange"
					>
						<el-option v-for="item in cardData" :key="item.id" :label="item.nickname" :value="item.id">
							<span>{{ item.nickname }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="sureAdd" :loading="cardLoading">确 定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="admissionStatus" title="添加住院人" width="40%">
			<el-form ref="admissionFormRef" :model="admissionForm" :rules="admissionRules" label-width="auto" label-position="left">
				<el-form-item label="就诊卡号" prop="card">
					<el-select
						v-model="admissionForm.card"
						placeholder="请选择就诊卡号"
						size="default"
						clearable
						filterable
						:loading="cardLoading"
						@visible-change="handleCardSelectVisibleChange"
					>
						<el-option v-for="item in cardData" :key="item.id" :label="item.nickname" :value="item.id">
							<span>{{ item.nickname }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="住院原因" prop="reason">
					<el-input v-model.trim="admissionForm.reason" type="textarea" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="admissionStatus = false">取消</el-button>
					<el-button type="primary" @click="sureAdmission" :loading="cardLoading">确认</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 头像预览弹窗 -->
		<el-dialog v-model="avatarPreviewVisible" title="患者头像" width="300px">
			<img :src="getPatientAvatar()" alt="患者头像" class="preview-avatar" />
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, onMounted, computed, reactive, toRaw, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { departmentList } from '/@/api/home/index';
import { roomList, addRoom, inHospital, outHospital, settlementDelete } from '/@/api/room/index';
import { checkIndex, checkAdd, checkPackage, medicineList } from '/@/api/room/index'; // 导入查房相关接口
import { cardList, cardIndex, settlementList, settlementAdd, upload } from '/@/api/room/index'; // 导入就诊卡列表接口
import { useUserInfo } from '/@/stores/userInfo'; // 导入用户信息store
import request from '/@/utils/request';
import { Plus, ArrowLeft, User, Picture } from '@element-plus/icons-vue';

// 新增：文件上传配置
const maxFileSize = ref(2 * 1024 * 1024); // 2MB，与服务器限制保持一致

// 视图切换标志
const isCheckRoomView = ref(false);
const isSettlementView = ref(false); // 新增：结算视图标志
const currentRoom = ref({});
const currentCard = ref(''); // 当前选中的就诊卡号
const patientCardInfo = ref({}); // 存储从就诊卡接口获取的患者信息
const checkRecords = ref([]);
const activeRecordId = ref(null);
const originalCheckForm = ref({}); // 用于恢复功能
const avatarPreviewVisible = ref(false);

// 表单历史记录数组，用于恢复功能
const formHistory = ref([]);

// 结算相关状态 - 新增
const settlementPatientInfo = ref({}); // 结算页面的患者信息
const doctorList = ref([]);
const doctorName = ref('');
const settlementData = ref([]);
const packageList = ref([]);
const drugList = ref([]);
const patientLoading = ref(true);
const settlementLoading = ref(true);
const doctorLoading = ref(false);
const packageLoading = ref(false);
const drugLoading = ref(false);

// 结算分页相关 - 新增
const settlementCurrentPage = ref(1);
const settlementPageSize = ref(10);

// 结算弹窗状态 - 新增
const addServiceVisible = ref(false);
const showCompleteOptions = ref(false);
const uploadExamVisible = ref(false);
const settlementAvatarPreviewVisible = ref(false);

// 结算表单数据 - 新增
const serviceForm = reactive({
	service_type: '',
	service_id: '',
	specification: 1,
	price: 0,
	subtotal: 0,
});

const examForm = reactive({
	name: '',
	result: '',
	file: null,
});

// 结算文件列表 - 新增
const examFileList = ref([]);

// 结算计算属性 - 新增
const filteredServiceOptions = computed(() => {
	if (serviceForm.service_type === '1') {
		return packageList.value;
	} else if (serviceForm.service_type === '2') {
		return drugList.value;
	}
	return [];
});
// 结算计算属性 - 增强调试
const paginatedSettlements = computed(() => {
	const start = (settlementCurrentPage.value - 1) * settlementPageSize.value;
	const end = start + settlementPageSize.value;
	const result = settlementData.value.slice(start, end);
	console.log('分页计算结果:', { start, end, total: settlementData.value.length, result });
	return result;
});

// 结算验证规则 - 新增
const serviceRules = reactive({
	service_type: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
	service_id: [{ required: true, message: '请选择服务名称', trigger: 'change' }],
	specification: [
		{ required: true, message: '请输入规格', trigger: 'blur' },
		{ type: 'number', min: 1, message: '规格必须大于0', trigger: 'blur' },
	],
});

const examRules = reactive({
	name: [{ required: true, message: '请输入体检名称', trigger: 'blur' }],
	result: [{ required: true, message: '请输入体检结果', trigger: 'blur' }],
	file: [{ required: true, message: '请上传体检报告', trigger: 'change' }],
});

// 状态相关
const statusValue = ref('');
const statusOptions = [
	{ value: 1, label: '空闲' },
	{ value: 2, label: '有人' },  // 值为2
];

// 弹窗状态
const dialogFormVisible = ref(false);
const admissionStatus = ref(false);
const imgStatus = ref(false);

// 科室相关
const departmentValue = ref('');
const departmentOptions = ref([]);
const departmentLoading = ref(false);

// 房间和床号
const roomNumber = ref('');
const bedNumber = ref('');

// 房间数据
const roomData = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(20);

// 默认图片
const DEFAULT_IMAGE = 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500';
const DEFAULT_AVATAR = 'https://cube.elemecdn.com/3/7c/3ea6beec64348a1667d2f721d5fcf76.png';
const BASE_IMAGE_URL = 'https://yiliao.kuxia.top';



// 表单相关
const formRef = ref();
const form = reactive({
	department: [],
	room_num: '',
	bed_num: '',
	img: '',
	card: '',
});

const admissionFormRef = ref();
const admissionForm = reactive({
	card: '',
	reason: '',
});

const checkFormRef = ref();
const checkForm = reactive({
	day: 1,
	situation: '',
	temperature: null,
	breathe: null,
	rate: null,
	blood: '',
	note: '',
	name: '',
	check_time: '',
	id: null,
});

// 添加查房表单验证规则
const checkRules = reactive({
	day: [{ required: true, message: '请输入查房次数', trigger: 'blur' }],
	situation: [{ required: true, message: '请输入查房情况', trigger: 'blur' }],
	temperature: [{ required: true, message: '请输入体温', trigger: 'blur' }],
	breathe: [{ required: true, message: '请输入呼吸次数', trigger: 'blur' }],
	rate: [{ required: true, message: '请输入心率', trigger: 'blur' }],
	blood: [{ required: true, message: '请输入血压', trigger: 'blur' }],
	note: [{ required: true, message: '请输入查房备注', trigger: 'blur' }],
	name: [{ required: true, message: '请输入查房医生姓名', trigger: 'blur' }],
	check_time: [{ required: true, message: '请选择查房日期', trigger: 'change' }],
});

// 结算表单引用 - 新增
const serviceFormRef = ref();
const examFormRef = ref();

// 为每个字段创建独立的历史记录
const fieldHistory = ref({});

// 记录字段修改顺序（仅当前会话）
const fieldModificationOrder = ref([]);

// 当前正在恢复的字段索引
const currentRestoreFieldIndex = ref(-1);

// 保存特定字段的值到历史记录
const saveFieldToHistory = (field, value) => {
	if (!fieldHistory.value[field]) {
		fieldHistory.value[field] = [];
	}
	// 只有当值发生变化时才保存
	const history = fieldHistory.value[field];
	if (history.length === 0 || JSON.stringify(history[history.length - 1]) !== JSON.stringify(value)) {
		history.push(JSON.parse(JSON.stringify(value)));
		// 记录字段修改顺序（仅当前会话），每次都添加，以便正确追踪修改顺序
		fieldModificationOrder.value.push(field);
	}
};


// 从历史记录中恢复特定字段的值
const restoreFieldFromHistory = (field) => {
	if (fieldHistory.value[field] && fieldHistory.value[field].length > 1) {
		// 获取倒数第二个历史记录（最后一个是最新的当前值）
		return JSON.parse(JSON.stringify(fieldHistory.value[field][fieldHistory.value[field].length - 2]));
	}
	return undefined;
};

// 失去焦点时处理体温输入
const handleTemperatureBlur = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('temperature', checkForm.temperature);

	if (checkForm.temperature !== null) {
		if (checkForm.temperature < 35) {
			checkForm.temperature = 35;
		} else if (checkForm.temperature > 42) {
			checkForm.temperature = 42;
		}
	}
};

// 失去焦点时处理呼吸次数输入
const handleBreatheBlur = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('breathe', checkForm.breathe);

	if (checkForm.breathe !== null) {
		if (checkForm.breathe < 12) {
			checkForm.breathe = 12;
		} else if (checkForm.breathe > 20) {
			checkForm.breathe = 20;
		}
	}
};

// 失去焦点时处理心率输入
const handleRateBlur = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('rate', checkForm.rate);

	if (checkForm.rate !== null) {
		if (checkForm.rate < 60) {
			checkForm.rate = 60;
		} else if (checkForm.rate > 100) {
			checkForm.rate = 100;
		}
	}
};

// 失去焦点时处理血压输入
const handleBloodBlur = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('blood', checkForm.blood);

	if (checkForm.blood) {
		const match = checkForm.blood.match(/^(\d{2,3})\/(\d{2,3})$/);
		if (match) {
			let systolic = parseInt(match[1]);
			let diastolic = parseInt(match[2]);

			// 限制收缩压范围 60-250
			if (systolic < 60) systolic = 60;
			if (systolic > 250) systolic = 250;

			// 限制舒张压范围 40-150
			if (diastolic < 40) diastolic = 40;
			if (diastolic > 150) diastolic = 150;

			checkForm.blood = `${systolic}/${diastolic}`;
			// 保存格式化后的血压值
			saveFieldToHistory('blood', checkForm.blood);
		} else {
			// 输入格式不正确时给出提示
			ElMessage.warning('血压格式应为如: 120/80');
			// 重置为上一次的正确值或空
			const lastValue = restoreFieldFromHistory('blood');
			checkForm.blood = lastValue || '';
		}
	}
};

// 处理查房备注输入
const handleNoteChange = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('note', checkForm.note);
};

// 处理查房医生姓名输入
const handleNameChange = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('name', checkForm.name);
};

// 处理查房情况输入
const handleSituationChange = () => {
	// 保存当前值到历史记录
	saveFieldToHistory('situation', checkForm.situation);
};

// 格式化血压输入
const formatBloodInput = (value) => {
	// 只允许数字和斜杠
	checkForm.blood = value.replace(/[^0-9/]/g, '');

	// 自动添加斜杠（当输入3个数字后自动添加）
	if (checkForm.blood.length === 3 && !checkForm.blood.includes('/')) {
		checkForm.blood = checkForm.blood + '/';
	}
};


// 获取时间线标签文本
const getTimelineLabel = (record) => {
	if (record.is_admission) {
		return '住院';
	} else {
		// 第n次查房显示为第n次查房
		return `第${record.day}次查房`;
	}
};

// 获取上次查房次数
const getLastCheckDay = () => {
	if (!checkRecords.value || checkRecords.value.length === 0) {
		return 0;
	}

	// 获取最大的查房次数，排除住院记录
	const checkRecordsOnly = checkRecords.value.filter(record => !record.is_admission);
	if (checkRecordsOnly.length === 0) {
		return 0;
	}

	const maxDay = Math.max(...checkRecordsOnly.map((record) => record.day || 0));
	return maxDay;
};

// 修改初始化新查房表单函数
const initNewCheckForm = () => {
	// 将当前表单状态保存到历史记录
	if (checkForm.day !== undefined) {
		// 确保不是初始状态
		if (!formHistory.value) {
			formHistory.value = [];
		}
		formHistory.value.push(JSON.parse(JSON.stringify(checkForm)));
	}

	// 计算新的查房次数（最大次数 + 1）
	const lastDay = getLastCheckDay();
	const newDay = lastDay >= 0 ? lastDay + 1 : 1; // 从1开始递增

	// 检查是否已经存在相同day值的记录
	const existingRecordIndex = checkRecords.value.findIndex(record => record.day === newDay && !record.is_admission);
	
	if (existingRecordIndex !== -1) {
		// 如果存在相同day值的记录，选中它
		const existingRecord = checkRecords.value[existingRecordIndex];
		selectRecord(existingRecord, existingRecordIndex);
	} else {
		// 如果不存在相同day值的记录，创建新记录
		Object.assign(checkForm, {
			day: newDay,
			situation: '',
			temperature: null,
			breathe: null,
			rate: null,
			blood: '',
			note: '',
			name: '',
			check_time: new Date().toISOString().split('T')[0], // 格式化为YYYY-MM-DD
			id: null,
			is_admission: undefined, // 不是住院记录
		});

		// 保存初始状态用于恢复
		originalCheckForm.value = JSON.parse(JSON.stringify(checkForm));

		// 创建新记录对象
		const newRecord = {
			day: newDay,
			situation: '',
			temperature: null,
			breathe: null,
			rate: null,
			blood: '',
			note: '',
			name: '',
			check_time: new Date().toISOString().split('T')[0],
			id: null,
			is_admission: undefined,
		};
		
		// 始终将新记录添加到数组末尾
		checkRecords.value.push(newRecord);
		
		// 选中新记录
		selectRecord(newRecord, checkRecords.value.length - 1);
	}
};

// 选择时间线记录 - 切换时更新查房次数
const selectRecord = (record, index) => {
	activeRecordId.value = record.id || index;

	// 重置恢复状态（仅影响当前记录）
	currentRestoreFieldIndex.value = -1;

	// 将当前表单状态保存到历史记录
	if (checkForm.day !== undefined) {
		// 确保不是初始状态
		saveFieldToHistory('day', checkForm.day);
		saveFieldToHistory('situation', checkForm.situation);
		saveFieldToHistory('temperature', checkForm.temperature);
		saveFieldToHistory('breathe', checkForm.breathe);
		saveFieldToHistory('rate', checkForm.rate);
		saveFieldToHistory('blood', checkForm.blood);
		saveFieldToHistory('note', checkForm.note);
		saveFieldToHistory('name', checkForm.name);
		saveFieldToHistory('check_time', checkForm.check_time);
	}

	// 填充表单数据，确保所有数值都正确转换
	Object.assign(checkForm, {
		day: record.day ? Number(record.day) : 0,
		situation: record.situation || '',
		temperature: record.temperature ? Number(record.temperature) : null,
		breathe: record.breathe ? Number(record.breathe) : null,
		rate: record.rate ? Number(record.rate) : null,
		blood: record.blood || '',
		note: record.note || '',
		name: record.name || '',
		check_time: record.check_time ? new Date(record.check_time).toISOString().split('T')[0] : '',
		id: record.id || null,
		is_admission: record.is_admission,
	});

	// 保存当前记录用于恢复
	originalCheckForm.value = JSON.parse(JSON.stringify(checkForm));
	
	// 清除表单验证错误提示
	if (checkFormRef.value) {
		nextTick(() => {
			checkFormRef.value.clearValidate();
		});
	}
};


// 直接处理搜索，不使用防抖
const handleSearch = () => {
	currentPage.value = 1;
	// 为了确保搜索立即生效，强制更新
	nextTick(() => {
		// 可以在这里添加额外的逻辑
	});
};

// 添加房间号输入失去焦点事件
const handleRoomNumberBlur = () => {
	handleSearch();
};

// 添加床号输入失去焦点事件
const handleBedNumberBlur = () => {
	handleSearch();
};

// 监听搜索条件变化
watch([statusValue, departmentValue, roomNumber, bedNumber], () => {
	handleSearch();
});

// 格式化房间号搜索输入（移除汉字）
const formatRoomNumberInput = (value) => {
	roomNumber.value = value.replace(/[\u4e00-\u9fa5]/g, '');
};

// 格式化床号搜索输入（移除汉字）
const formatBedNumberInput = (value) => {
	bedNumber.value = value.replace(/[\u4e00-\u9fa5]/g, '');
};

// 添加计算属性用于过滤房间列表
const filteredRoomData = computed(() => {
	let filtered = roomData.value;
	
	// 按状态筛选
	if (statusValue.value !== '' && statusValue.value !== null && statusValue.value !== undefined) {
		// 注意：这里的状态值需要与实际数据匹配
		// 根据代码，statusValue.value 为 1 表示空闲，2 表示有人
		filtered = filtered.filter(item => {
			// item.room_status 为 1 表示空房，2 表示已占用
			if (statusValue.value === 1) {
				// 空房
				return item.room_status === 1;
			} else if (statusValue.value === 2) {
				// 已占用
				return item.room_status === 2;
			}
			return true;
		});
	}
	
	// 按科室筛选
	if (departmentValue.value !== '' && departmentValue.value !== null && departmentValue.value !== undefined) {
		filtered = filtered.filter(item => 
			// 确保比较的是相同类型的数据
			String(item.department) === String(departmentValue.value)
		);
	}
	
	// 按房间号筛选
	if (roomNumber.value !== '' && roomNumber.value !== null && roomNumber.value !== undefined) {
		filtered = filtered.filter(item => {
			// 确保 item.room_num 存在并进行不区分大小写的包含匹配
			if (item.room_num) {
				return String(item.room_num).toLowerCase().includes(String(roomNumber.value).toLowerCase());
			}
			return false;
		});
	}
	
	// 按床号筛选
	if (bedNumber.value !== '' && bedNumber.value !== null && bedNumber.value !== undefined) {
		filtered = filtered.filter(item => {
			// 确保 item.bed_num 存在并进行不区分大小写的包含匹配
			if (item.bed_num) {
				return String(item.bed_num).toLowerCase().includes(String(bedNumber.value).toLowerCase());
			}
			return false;
		});
	}
	
	return filtered;
});

// 添加分页计算属性
const paginatedRoomData = computed(() => {
	const start = (currentPage.value - 1) * pageSize.value;
	const end = start + pageSize.value;
	return filteredRoomData.value.slice(start, end);
});

// 添加计算总页数的计算属性
const totalPages = computed(() => {
	return Math.ceil(filteredRoomData.value.length / pageSize.value);
});

// 处理页面大小变化
const handleSizeChange = (val) => {
	pageSize.value = val;
	currentPage.value = 1;
};

// 处理当前页变化
const handleCurrentChange = (val) => {
	currentPage.value = val;
};

// 修改其他输入框的处理函数，添加历史记录功能
const handleDayChange = () => {
	saveFieldToHistory('day', checkForm.day);
};




const selectedRoom = ref({});

// 就诊卡数据
const cardData = ref([]);
const cardLoading = ref(false);

// 获取就诊卡列表 - 优化版本
const getCardList = async () => {
	try {
		cardLoading.value = true;
		const res = await cardIndex().signIn({});

		if (res.code === 1) {
			// 根据实际返回的数据结构调整
			let cardListData = [];
			if (res.data && Array.isArray(res.data)) {
				cardListData = res.data;
			} else if (res.data && res.data.records && Array.isArray(res.data.records)) {
				cardListData = res.data.records;
			} else if (res.data && res.data.data && Array.isArray(res.data.data)) {
				cardListData = res.data.data;
			}

			// 处理数据，确保每项都有id和name字段
			cardData.value = cardListData.map((item) => {
				// 处理各种可能的字段名
				const id = item.card || item.id || item.card_id || '';
				const name = item.nickname || item.name || item.patient_name || '未知患者';
				const nickname = item.nickname || item.name || item.patient_name || '未知患者';

				return {
					id: id,
					name: `${nickname} (${id || '无ID'})`,
					nickname: nickname, // 保留昵称用于住院弹窗显示
				};
			});

			// 如果数据为空，显示提示信息
			if (cardData.value.length === 0) {
				ElMessage.info('暂无就诊卡数据');
			}
		} else {
			ElMessage.error(res.msg || '获取就诊卡列表失败');
			cardData.value = [];
		}
	} catch (error) {
		console.error('获取就诊卡列表异常:', error);
		// 提供更详细的错误信息
		if (error.response) {
			// 服务器返回了错误响应
			if (error.response.status === 500) {
				ElMessage.error('服务器内部错误，请联系管理员');
			} else {
				ElMessage.error(`请求失败 (${error.response.status}): ${error.response.statusText}`);
			}
		} else if (error.request) {
			// 请求已发出但没有收到响应
			ElMessage.error('网络连接错误，请检查网络');
		} else {
			// 其他错误
			ElMessage.error('请求配置错误: ' + error.message);
		}
		cardData.value = [];
	} finally {
		cardLoading.value = false;
	}
};

// 上传相关
const dialogImageUrl = ref('');
const fileList = ref([]);
const uploadRef = ref();

// 级联选择器配置
const cascaderProps = {
	value: 'id',
	label: 'name',
	children: 'children',
	emitPath: false,
};

// 验证规则
const rules = reactive({
	department: [{ required: true, message: '请选择科室', trigger: 'change' }],
	room_num: [
		{ required: true, message: '请输入房间号', trigger: 'blur' },
		{ pattern: /^[A-Za-z0-9]+$/, message: '房间号只能包含字母和数字', trigger: 'blur' },
	],
	bed_num: [
		{ required: true, message: '请输入床号', trigger: 'blur' },
		{ pattern: /^[A-Za-z0-9]+$/, message: '床号只能包含字母和数字', trigger: 'blur' },
	],
	img: [{ required: true, message: '请上传图片', trigger: 'change' }],
	card: [{ required: true, message: '请选择就诊卡号', trigger: 'change' }],
});

const admissionRules = reactive({
	card: [{ required: true, message: '请选择就诊卡号', trigger: 'change' }],
	reason: [{ required: true, message: '请输入住院原因', trigger: 'blur' }],
});



// 格式化新增房间中的房间号输入（移除汉字）
const formatRoomInput = (value) => {
	form.room_num = value.replace(/[\u4e00-\u9fa5]/g, '');
};

// 格式化新增房间中的床号输入（移除汉字）
const formatBedInput = (value) => {
	form.bed_num = value.replace(/[\u4e00-\u9fa5]/g, '');
};

// 获取科室列表
const getDepartmentList = async () => {
	try {
		departmentLoading.value = true;
		const res = await departmentList().signIn({});

		if (res.code === 1) {
			if (res.data && Array.isArray(res.data)) {
				departmentOptions.value = res.data.map((item) => ({
					id: item.id,
					name: item.name || item.depart_name || '未知科室',
					children: item.children || [],
				}));
			} else {
				departmentOptions.value = [];
			}
		} else {
			console.error('获取科室列表失败:', res.msg || '未知错误');
			departmentOptions.value = [];
		}
	} catch (error) {
		console.error('获取科室列表异常:', error);
		departmentOptions.value = [];
	} finally {
		departmentLoading.value = false;
	}
};

// 递归查找科室名称
const findDepartment = (departments, targetId) => {
	for (const dept of departments) {
		if (dept.id == targetId) {
			return dept.name;
		}
		if (dept.children && dept.children.length > 0) {
			const found = findDepartment(dept.children, targetId);
			if (found) {
				return found;
			}
		}
	}
	return null;
};

// 根据科室ID获取科室名称
const getDepartmentName = (departId) => {
	if (!departId) return '未知科室';
	const departmentName = findDepartment(departmentOptions.value, departId);
	return departmentName || '未知科室';
};

// 获取图片完整URL
const getImageUrl = (imgPath) => {
	if (!imgPath) return DEFAULT_IMAGE;
	return `${BASE_IMAGE_URL}${imgPath}`;
};

// 获取患者头像
const getPatientAvatar = () => {
	if (patientCardInfo.value.avatar) {
		return `${BASE_IMAGE_URL}${patientCardInfo.value.avatar}`;
	}
	return DEFAULT_AVATAR;
};

// 预览头像
const previewAvatar = () => {
	avatarPreviewVisible.value = true;
};

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return '';
	const date = new Date(dateString);
	return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date
		.getHours()
		.toString()
		.padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 根据出生日期计算年龄
const calculateAge = (birthDateStr) => {
	if (!birthDateStr) return null;

	// 处理可能的日期格式问题
	const birthDate = new Date(birthDateStr);
	if (isNaN(birthDate.getTime())) {
		// 尝试处理"1004-11-03"这样的年份小于1970的情况
		const parts = birthDateStr.split('-');
		if (parts.length === 3) {
			const year = parseInt(parts[0]);
			const month = parseInt(parts[1]) - 1;
			const day = parseInt(parts[2]);

			const today = new Date();
			let age = today.getFullYear() - year;
			const monthDiff = today.getMonth() - month;

			if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < day)) {
				age--;
			}

			return age > 0 ? age : 0;
		}
		return null;
	}

	const today = new Date();
	let age = today.getFullYear() - birthDate.getFullYear();
	const monthDiff = today.getMonth() - birthDate.getMonth();

	if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
		age--;
	}

	return age > 0 ? age : 0;
};

// 获取住院状态文本
const getHosStatusText = (status) => {
	switch (status) {
		case 1:
			return '未住院';
		case 2:
			return '住院中';
		case 3:
			return '已出院';
		default:
			return '未知状态';
	}
};

// 获取状态文本
const getStatusText = (status) => {
	return status == 1 ? '空闲' : '有人';
};

// 获取状态样式类
const getStatusClass = (status) => {
	return status == 1 ? 'status-free' : 'status-occupied';
};

// 获取房间列表
const getRoomList = async () => {
	try {
		const res = await roomList().signIn({});

		if (res.code === 1) {
			roomData.value = res.data && Array.isArray(res.data) ? res.data : [];
		} else {
			console.error('获取房间列表失败:', res.msg || '未知错误');
			roomData.value = [];
		}
	} catch (error) {
		console.error('获取房间列表异常:', error);
		roomData.value = [];
	}
};
// 计算记录在排序后数组中的索引
const getIndexInSorted = (record, records) => {
	const sortedRecords = [...records].sort((a, b) => new Date(a.check_time) - new Date(b.check_time));
	return sortedRecords.findIndex((r) => r.id === record.id);
};

// 获取查房记录
const getCheckRecords = async (room) => {
	try {
		// 先获取就诊卡信息
		await getCardInfo(currentCard.value);

		// 构造请求参数，确保都是字符串类型
		const requestParams = {
			card: currentCard.value || '',
			room_id: room.id.toString(),
			bed: room.bed_num ? room.bed_num.toString() : '',
		};

		const res = await checkIndex().signIn(requestParams);

		if (res.code === 1) {
			// 根据实际返回的数据结构调整
			if (res.data && Array.isArray(res.data)) {
				// 如果直接返回数组
				checkRecords.value = res.data;
			} else if (res.data && res.data.records && Array.isArray(res.data.records)) {
				// 如果返回对象包含records字段
				checkRecords.value = res.data.records;
			} else if (res.data && res.data.data && Array.isArray(res.data.data)) {
				// 如果返回对象包含data字段
				checkRecords.value = res.data.data;
			} else {
				checkRecords.value = [];
			}

			// 确保所有记录都有day字段
			checkRecords.value.forEach(record => {
				if (record.day === undefined || record.day === null) {
					record.day = 0;
				}
			});

			// 查找明确标记为住院的记录
			const existingAdmission = checkRecords.value.find(record => record.is_admission);

			// 如果没有明确的住院记录，则查找day为0的记录作为住院记录
			if (!existingAdmission) {
				const zeroDayRecord = checkRecords.value.find(record => record.day === 0);
				if (zeroDayRecord) {
					// 将day为0的记录标记为住院记录
					zeroDayRecord.is_admission = 1;
					zeroDayRecord.note = zeroDayRecord.note || '患者办理住院';
				} else {
					// 如果没有day为0的记录，创建新的住院记录
					const admissionRecord = {
						day: 0,
						situation: '',
						temperature: null,
						breathe: null,
						rate: null,
						blood: '',
						note: '患者办理住院',
						name: '',
						check_time: new Date().toISOString().split('T')[0],
						id: null,
						is_admission: 1,
					};
					checkRecords.value.unshift(admissionRecord);
				}
			}

			// 重新排序记录，住院记录在最前面，然后按day排序
			checkRecords.value.sort((a, b) => {
				// 住院记录排在最前面
				if (a.is_admission && !b.is_admission) return -1;
				if (!a.is_admission && b.is_admission) return 1;
				// 都是住院记录或都不是住院记录，按day排序
				return (a.day || 0) - (b.day || 0);
			});

			// 去重处理，确保没有重复的day值记录（除了住院记录）
			const seenDays = new Set();
			const uniqueRecords = [];
			
			for (const record of checkRecords.value) {
				// 住院记录始终保留
				if (record.is_admission) {
					uniqueRecords.push(record);
					continue;
				}
				
				// 对于非住院记录，检查day值是否已存在
				if (!seenDays.has(record.day)) {
					seenDays.add(record.day);
					uniqueRecords.push(record);
				}
				// 如果day值已存在，则跳过该记录（去重）
			}
			
			checkRecords.value = uniqueRecords;

			// 如果有查房记录，默认选中第一条
			if (checkRecords.value.length > 0) {
				const firstRecord = checkRecords.value[0];
				selectRecord(firstRecord, 0);
			} else {
				// 没有记录时初始化表单
				initNewCheckForm();
			}
		} else {
			ElMessage.error(res.msg || '获取查房记录失败');
			checkRecords.value = [];
		}
	} catch (error) {
		console.error('获取查房记录异常:', error);
		ElMessage.error('获取查房记录失败，请重试');
		checkRecords.value = [];
	}
};

// 查房处理 - 接收就诊卡号参数
const handleCheckRoom = async (room, card) => {
	if (room.room_status === 1) {
		ElMessage.warning('空房不能进行查房操作');
		return;
	}

	// 保存就诊卡号
	currentCard.value = card;
	currentRoom.value = room;
	isCheckRoomView.value = true;
	isSettlementView.value = false;
	
	// 重置恢复相关状态（确保不与其他数据联动）
	fieldHistory.value = {};
	fieldModificationOrder.value = [];
	currentRestoreFieldIndex.value = -1;
	
	// 确保在获取记录前设置好currentRoom
	await nextTick();
	await getCheckRecords(room);

	// 如果没有任何查房记录（包括住院记录），初始化一条新的住院记录
	if (checkRecords.value.length === 0) {
		// 创建住院记录
		const admissionRecord = {
			day: 0,
			situation: '',
			temperature: null,
			breathe: null,
			rate: null,
			blood: '',
			note: '患者办理住院',
			name: '',
			check_time: new Date().toISOString().split('T')[0],
			id: null,
			is_admission: 1,
		};
		checkRecords.value.push(admissionRecord);
		
		// 初始化第一条查房记录
		initNewCheckForm();
	} 
	// 如果有记录，自动添加新的时间节点
	else {
		// 自动添加新的时间节点
		initNewCheckForm();
	}
};

// 结算处理 - 修改为显示结算视图 (增强调试)
const handleSettle = async (room, card) => {
	if (room.room_status === 1) {
		ElMessage.warning('空房不能进行结算操作');
		return;
	}

	// 保存就诊卡号和房间信息
	currentCard.value = card;
	currentRoom.value = room;
	isSettlementView.value = true;
	isCheckRoomView.value = false;
	console.log('结算处理参数:', { room, card });

	// 加载结算所需数据
	await nextTick();
	await getSettlementPatientInfo();
	await getSettlementList(room);

	// 预加载服务列表
	if (packageList.value.length === 0) {
		getPackageList();
	}
	if (drugList.value.length === 0) {
		getDrugList();
	}
};

// 返回上一页 - 修改为适应多视图切换
const goBack = () => {
	if (isCheckRoomView.value) {
		isCheckRoomView.value = false;
	} else if (isSettlementView.value) {
		isSettlementView.value = false;
	}

	currentRoom.value = {};
	currentCard.value = '';
	checkRecords.value = [];
	patientCardInfo.value = {};
	settlementPatientInfo.value = {};
	settlementData.value = [];

	// 清空表单历史记录
	formHistory.value = [];
	
	// 重置查房表单
	Object.assign(checkForm, {
		day: 1,
		situation: '',
		temperature: null,
		breathe: null,
		rate: null,
		blood: '',
		note: '',
		name: '',
		check_time: '',
		id: null,
	});
	
	// 重置原始表单
	originalCheckForm.value = null;
	
	// 重置选中的记录ID
	activeRecordId.value = null;
};

// 保存查房记录
const saveCheckRecord = () => {
	checkFormRef.value.validate(async (valid) => {
		if (valid) {
			try {
				// 保存当前表单状态到历史记录
				saveFieldToHistory('day', checkForm.day);
				saveFieldToHistory('situation', checkForm.situation);
				saveFieldToHistory('temperature', checkForm.temperature);
				saveFieldToHistory('breathe', checkForm.breathe);
				saveFieldToHistory('rate', checkForm.rate);
				saveFieldToHistory('blood', checkForm.blood);
				saveFieldToHistory('note', checkForm.note);
				saveFieldToHistory('name', checkForm.name);
				saveFieldToHistory('check_time', checkForm.check_time);

				// 构造请求参数，确保所有参数都是字符串类型并且符合接口要求
				const requestData = {
					room_id: currentRoom.value.id ? currentRoom.value.id.toString() : '',
					name: checkForm.name ? checkForm.name.toString() : '',
					temperature: checkForm.temperature !== null ? checkForm.temperature.toString() : '',
					breathe: checkForm.breathe !== null ? checkForm.breathe.toString() : '',
					rate: checkForm.rate !== null ? checkForm.rate.toString() : '',
					blood: checkForm.blood ? checkForm.blood.toString() : '',
					note: checkForm.note ? checkForm.note.toString() : '',
					check_time: checkForm.check_time ? checkForm.check_time.toString() : '',
					detart: getDepartmentName(currentRoom.value.depart_id) ? getDepartmentName(currentRoom.value.depart_id).toString() : '',
					card: currentCard.value ? currentCard.value.toString() : '',
					day: checkForm.day ? checkForm.day.toString() : '1',
					bed: currentRoom.value.bed_num ? currentRoom.value.bed_num.toString() : '',
					// 只有明确标记为住院记录时才添加is_admission参数
					...(checkForm.is_admission === 1 && { is_admission: '1' })
				};

				// 验证所有必填参数是否存在
				const requiredFields = ['room_id', 'name', 'temperature', 'breathe', 'rate', 'blood', 'note', 'check_time', 'detart', 'card', 'day', 'bed'];
				const missingFields = requiredFields.filter((field) => !requestData[field] || requestData[field] === '');

				if (missingFields.length > 0) {
					ElMessage.error(`缺少必填参数: ${missingFields.join(', ')}`);
					console.log('查房请求数据:', requestData); // 调试信息
					return;
				}

				console.log('查房请求数据:', requestData); // 调试信息

				const res = await checkAdd().signIn(requestData);

				if (res.code === 1) {
					ElMessage.success('查房记录保存成功');

					// 更新本地记录列表而不是重新获取
					if (checkForm.id) {
						// 更新现有记录
						const recordIndex = checkRecords.value.findIndex((record) => record.id === checkForm.id);
						if (recordIndex !== -1) {
							checkRecords.value[recordIndex] = {
								...checkRecords.value[recordIndex],
								...checkForm,
								id: res.data?.id || checkForm.id, // 更新ID
							};
						}
					} else {
						// 添加新记录
						const newRecord = {
							...checkForm,
							id: res.data?.id || null, // 使用服务器返回的ID
						};
						// 检查是否已经存在相同day值的记录
						const existingRecordIndex = checkRecords.value.findIndex(record => record.day === newRecord.day && !record.is_admission);
						
						if (existingRecordIndex !== -1) {
							// 如果存在相同day值的记录，更新它而不是添加新记录
							checkRecords.value[existingRecordIndex] = {
								...checkRecords.value[existingRecordIndex],
								...newRecord
							};
						} else {
							// 总是将新记录添加到数组末尾
							checkRecords.value.push(newRecord);
						}
					}

					// 保持当前选中状态
					activeRecordId.value = checkForm.id || res.data?.id || null;
					
					// 保存成功后清空恢复历史
					fieldHistory.value = {};
					fieldModificationOrder.value = [];
					currentRestoreFieldIndex.value = -1;
					
					// 保存成功后不再自动初始化下一个查房记录
					// 新的时间节点会在点击查房按钮时自动添加
				} else {
					ElMessage.error(res.msg || '保存失败');
				}
			} catch (error) {
				console.error('保存查房记录异常:', error);
				ElMessage.error('保存失败，请重试');
			}
		} else {
			ElMessage.error('请完善并修正表单信息');
			// 添加滚动到第一个错误字段的功能
			nextTick(() => {
				const firstErrorElement = document.querySelector('.el-form-item.is-error');
				if (firstErrorElement) {
					firstErrorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
				}
			});
			return false;
		}
	});
};

// 重置表单
const resetForm = () => {
	// 保存当前表单状态到历史记录
	if (!formHistory.value) {
		formHistory.value = [];
	}
	formHistory.value.push(JSON.parse(JSON.stringify(checkForm)));

	// 只重置当前表单数据，不创建新记录
	Object.assign(checkForm, {
		day: checkForm.day, // 保持当前的查房次数不变
		situation: '',
		temperature: null,
		breathe: null,
		rate: null,
		blood: '',
		note: '',
		name: '',
		check_time: new Date().toISOString().split('T')[0],
		id: checkForm.id, // 保持当前记录ID不变
		is_admission: checkForm.is_admission, // 保持住院记录标识不变
	});
	
	// 清除表单验证错误提示
	if (checkFormRef.value) {
		nextTick(() => {
			checkFormRef.value.clearValidate();
		});
	}
};

// 恢复表单 - 实现按输入顺序倒序恢复功能（仅当前会话）
const restoreForm = () => {
	// 过滤掉 day 和 check_time 字段，获取可恢复的字段历史记录
	const restoreableHistory = fieldModificationOrder.value.filter(field => 
		field !== 'day' && field !== 'check_time'
	);
	
	// 检查是否有历史记录可以恢复
	let hasHistory = false;
	for (const field of restoreableHistory) {
		if (fieldHistory.value[field] && fieldHistory.value[field].length > 1) {
			hasHistory = true;
			break;
		}
	}

	if (!hasHistory) {
		ElMessage.info('没有可恢复的内容');
		return;
	}

	// 如果当前没有正在恢复的字段，则开始按输入顺序倒序恢复
	if (currentRestoreFieldIndex.value === -1) {
		if (restoreableHistory.length === 0) {
			ElMessage.info('没有可恢复的内容');
			return;
		}
		
		// 设置当前要恢复的字段为最后一个修改的字段（倒序）
		currentRestoreFieldIndex.value = restoreableHistory.length - 1;
	} else {
		// 移动到上一个字段（倒序）
		currentRestoreFieldIndex.value--;
	}
	
	// 如果没有更多字段可恢复
	if (currentRestoreFieldIndex.value < 0) {
		ElMessage.info('所有可恢复字段已完成恢复');
		currentRestoreFieldIndex.value = -1;
		return;
	}
	
	// 获取当前要恢复的字段
	const field = restoreableHistory[currentRestoreFieldIndex.value];
	
	// 尝试从历史记录中恢复该字段的值
	const restoredValue = restoreFieldFromHistory(field);
	
	if (restoredValue !== undefined) {
		// 恢复字段值
		checkForm[field] = restoredValue;
		
		// 从历史记录中也移除已恢复的值
		if (fieldHistory.value[field] && fieldHistory.value[field].length > 1) {
			fieldHistory.value[field].pop();
		}
		
		// 根据字段显示不同的提示信息
		const fieldLabels = {
			day: '查房次数',
			situation: '查房情况',
			temperature: '体温',
			breathe: '呼吸次数',
			rate: '心率',
			blood: '血压',
			note: '查房备注',
			name: '查房医生',
			check_time: '查房日期',
		};
		
		// ElMessage.success(`已恢复"${fieldLabels[field] || field}"字段的上一次数据`);
	} else {
		// 如果当前字段没有历史记录可恢复，则恢复到初始值
		if (originalCheckForm.value && originalCheckForm.value[field] !== undefined) {
			checkForm[field] = originalCheckForm.value[field];
			
			const fieldLabels = {
				day: '查房次数',
				situation: '查房情况',
				temperature: '体温',
				breathe: '呼吸次数',
				rate: '心率',
				blood: '血压',
				note: '查房备注',
				name: '查房医生',
				check_time: '查房日期',
			};
			
			ElMessage.success(`"${fieldLabels[field] || field}"字段已恢复到初始值`);
		} else {
			ElMessage.info(`"${field}"字段没有可恢复的内容`);
		}
	}
	
	// 清除表单验证错误提示
	if (checkFormRef.value) {
		nextTick(() => {
			checkFormRef.value.clearValidate();
		});
	}
};

// 打开新增弹窗
const handleAdd = () => {
	resetForm();
	dialogFormVisible.value = true;
	// 如果还没有加载过就诊卡数据，则加载数据
	if (cardData.value.length === 0 && !cardLoading.value) {
		getCardList();
	}
};

const handleRemove = (file) => {
	form.img = '';
	fileList.value = [];
};

// 格式化文件大小显示
const formatFileSize = (bytes) => {
	if (bytes === 0) return '0 Bytes';
	const k = 1024;
	const sizes = ['Bytes', 'KB', 'MB', 'GB'];
	const i = Math.floor(Math.log(bytes) / Math.log(k));
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 上传图片 - 优化版本
const handleUpload = (file) => {
	console.log(file);

	// 检查是否有文件
	if (!file || !file.raw) {
		ElMessage.warning('请选择要上传的文件');
		fileList.value = [];
		return;
	}

	// 检查文件类型
	const isJPG = file.raw.type === 'image/jpeg';
	const isPNG = file.raw.type === 'image/png';

	if (!isJPG && !isPNG) {
		ElMessage.error('只能上传 JPG/PNG 格式的图片!');
		fileList.value = [];
		return;
	}

	// 检查文件大小
	const isLt2M = file.raw.size / 1024 / 1024 < 2;
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		fileList.value = [];
		return;
	}

	// 显示上传中状态
	const loading = ElMessage({
		message: '正在上传...',
		type: 'info',
		duration: 0,
		showClose: true,
	});

	const formData = new FormData();
	formData.append('file', file.raw);
	console.log('准备上传的表单数据:', formData);

	// 使用特殊的配置来处理文件上传，避免被默认的Content-Type覆盖
	upload()
		.signIn(formData)
		.then((res) => {
			// 关闭上传中提示
			loading.close();

			if (res.code === 1) {
				const fileUrl = res.data.url || '';
				fileList.value = [
					{
						name: file.name,
						url: BASE_IMAGE_URL + fileUrl,
						size: file.size,
						raw: file.raw,
					},
				];
				form.img = fileUrl;
				ElMessage.success('图片上传成功');
				if (formRef.value) {
					formRef.value.clearValidate('img');
				}
			} else {
				// 处理服务器返回的错误
				if (res.msg && res.msg.includes('limit')) {
					ElMessage.error(`服务器上传限制：文件不能超过${maxFileSize.value / 1024 / 1024}MB`);
				} else {
					ElMessage.error(res.msg || '上传失败，请重试');
				}
				fileList.value = [];
			}
		})
		.catch((error) => {
			// 关闭上传中提示
			loading.close();

			console.error('上传请求失败:', error);
			if (error.message && error.message.includes('limit')) {
				ElMessage.error(`服务器上传限制超出，请选择小于${maxFileSize.value / 1024 / 1024}MB的文件`);
			} else if (error.message && error.message.includes('Network Error')) {
				ElMessage.error('网络错误，请检查网络连接');
			} else {
				ElMessage.error('上传失败，请重试');
			}
			fileList.value = [];
		});
};

// 初始化表单数据并清除验证状态
const resetAllForms = () => {
	// 重置主表单
	Object.assign(form, {
		department: [],
		room_num: '',
		bed_num: '',
		img: '',
		card: '',
	});

	// 重置住院表单
	Object.assign(admissionForm, {
		card: '',
		reason: '',
	});

	// 清空文件列表
	fileList.value = [];

	// 清除验证
	if (formRef.value) {
		formRef.value.resetFields();
	}

	if (admissionFormRef.value) {
		admissionFormRef.value.resetFields();
	}
};

// 新增房间提交处理
const sureAdd = () => {
	formRef.value.validate((valid) => {
		if (valid) {
			// 检查是否已上传图片
			if (!form.img) {
				ElMessage.error('请上传房间图片');
				return;
			}

			// 获取用户ID（从store中获取）
			const userInfoStore = useUserInfo();
			console.log('用户信息:', userInfoStore.userInfos); // 调试信息
			const userId = userInfoStore.userInfos.id || userInfoStore.userInfos.userId || '43'; // 添加备选方案和默认值

			const requestData = {
				department: form.department,
				room_num: form.room_num,
				bed_num: form.bed_num,
				img: form.img,
				card: form.card || '', // 可选参数
				room_status: '1', // 空闲状态
				hospital_status: '1', // 住院状态（1表示未住院）
				user_id: userId.toString(), // 用户ID
			};

			console.log('新增房间请求数据:', requestData); // 调试信息

			addRoom()
				.signIn(requestData)
				.then((res) => {
					if (res.code === 1) {
						ElMessage.success('添加成功');
						dialogFormVisible.value = false;
						getRoomList(); // 重新获取列表
					} else {
						ElMessage.error(res.msg || '添加失败');
					}
				})
				.catch((error) => {
					console.error('操作失败:', error);
					ElMessage.error('操作失败，请稍后重试');
				});
		} else {
			ElMessage.error('请完善必填信息');
			return false;
		}
	});
};

// 处理就诊卡选择框显示变化
const handleCardSelectVisibleChange = (visible) => {
	// 当下拉框打开时，如果还没有加载过数据，则加载数据
	if (visible && cardData.value.length === 0 && !cardLoading.value) {
		getCardList();
	}
};

// 住院处理
const handleAdmit = (room) => {
	console.log('选中的房间信息:', room); // 调试信息
	selectedRoom.value = room;
	resetAllForms();
	admissionStatus.value = true;
	// 如果还没有加载过就诊卡数据，则加载数据
	if (cardData.value.length === 0 && !cardLoading.value) {
		getCardList();
	}
};

// 办理住院确定提交
const sureAdmission = () => {
	admissionFormRef.value.validate((valid) => {
		if (valid) {
			// 先获取就诊卡信息，确保我们有最新的user_id
			getCardInfo(admissionForm.card).then(() => {
				// 获取用户ID（从store中获取）
				const userInfoStore = useUserInfo();
				console.log('用户信息:', userInfoStore.userInfos); // 调试信息
				const userId = userInfoStore.userInfos.id || userInfoStore.userInfos.userId || patientCardInfo.value.user_id || '43'; // 多种获取方式

				// 打印房间信息以调试
				console.log('选中的房间信息:', selectedRoom.value);

				const requestData = {
					id: selectedRoom.value.id ? selectedRoom.value.id.toString() : '', // 列表id
					room_num: selectedRoom.value.room_num ? selectedRoom.value.room_num.toString() : '', // 房间号
					bed_num: selectedRoom.value.bed_num ? selectedRoom.value.bed_num.toString() : '', // 床号
					department: selectedRoom.value.depart_id
						? selectedRoom.value.depart_id.toString()
						: selectedRoom.value.department
						? selectedRoom.value.department.toString()
						: '', // 科室id
					card: admissionForm.card ? admissionForm.card.toString() : '', // 就诊卡号
					user_id: userId.toString(), // 用户id
					hospital_status: '2', // 住院状态（2表示住院中）
					room_status: '2', // 房间状态（2表示已占用）
					reason: admissionForm.reason ? admissionForm.reason.toString() : '', // 住院原因
				};

				// 检查必填参数是否完整
				const requiredFields = ['id', 'room_num', 'bed_num', 'department', 'room_status'];
				const missingFields = requiredFields.filter((field) => !requestData[field]);

				if (missingFields.length > 0) {
					ElMessage.error(`缺少必填参数: ${missingFields.join(', ')}`);
					console.log('房间信息:', selectedRoom.value); // 调试信息
					console.log('请求数据:', requestData); // 调试信息
					return;
				}

				console.log('住院办理请求数据:', requestData); // 调试信息

				inHospital()
					.signIn(requestData)
					.then(async (res) => {
						if (res.code === 1) {
							ElMessage.success('住院办理成功');
							admissionStatus.value = false;
							getRoomList(); // 重新获取列表

							// 创建住院记录作为第一次查房
							await createAdmissionCheckRecord(requestData);
						} else {
							ElMessage.error(res.msg || '办理失败');
						}
					})
					.catch((error) => {
						console.error('操作失败:', error);
						ElMessage.error('操作失败，请稍后重试');
					});
			});
		} else {
			ElMessage.error('请完善必填信息');
			return false;
		}
	});
};
// 创建住院时的查房记录（办理住院）
const createAdmissionCheckRecord = async (admissionData) => {
	try {
		const requestData = {
			room_id: admissionData.id,
			name: '', // 查房医生姓名，住院时可以为空
			temperature: '', // 体温
			breathe: '', // 呼吸
			rate: '', // 心率
			blood: '', // 血压
			note: '患者办理住院', // 查房备注
			check_time: new Date().toISOString().split('T')[0], // 住院时间
			detart: getDepartmentName(selectedRoom.value.depart_id) || '', // 科室
			card: admissionData.card, // 就诊卡号
			day: 0, // 住院记录为第0次查房
			bed: admissionData.bed_num, // 床号
			is_admission: 1, // 标记为住院记录
		};

		const res = await checkAdd().signIn(requestData);
		if (res.code === 1) {
			console.log('住院查房记录创建成功');
		} else {
			console.error('住院查房记录创建失败:', res.msg);
		}
	} catch (error) {
		console.error('创建住院查房记录异常:', error);
	}
};

// 分页切换
const handlePageChange = (page) => {
	currentPage.value = page;
};

// 结算分页切换 - 新增
const handleSettlementPageChange = (page) => {
	settlementCurrentPage.value = page;
};

// 结算相关方法 - 新增

// 方法：获取结算患者信息
const getSettlementPatientInfo = async () => {
	try {
		patientLoading.value = true;
		const res = await cardList().signIn({ card: currentCard.value });
		console.log(res);

		if (res.code === 1) {
			// 处理不同的数据结构
			if (Array.isArray(res.data) && res.data.length > 0) {
				settlementPatientInfo.value = res.data[0];
			} else if (res.data && typeof res.data === 'object') {
				settlementPatientInfo.value = res.data;
			} else {
				settlementPatientInfo.value = res.data || {};
			}

			// 如果有医生ID，获取医生信息
			if (settlementPatientInfo.value.doctor_id) {
				getDoctorInfo(settlementPatientInfo.value.doctor_id);
			}
		} else {
			ElMessage.error(res.msg || '获取患者信息失败');
			settlementPatientInfo.value = {};
		}
	} catch (error) {
		console.error('获取患者信息异常:', error);
		ElMessage.error('获取患者信息失败，请重试');
		settlementPatientInfo.value = {};
	} finally {
		patientLoading.value = false;
	}
};

// 方法：获取医生信息
const getDoctorInfo = async (doctorId) => {
	try {
		doctorLoading.value = true;
		const res = await request({
			url: '/pc/doctor/index',
			method: 'post',
		});

		if (res.code === 1) {
			doctorList.value = res.data || [];
			// 查找匹配的医生姓名
			const doctor = doctorList.value.find((item) => item.id == doctorId);
			doctorName.value = doctor ? doctor.name : '未知医生';
		} else {
			console.error('获取医生列表失败:', res.msg || '未知错误');
			doctorName.value = '暂无';
		}
	} catch (error) {
		console.error('获取医生列表异常:', error);
		doctorName.value = '暂无';
	} finally {
		doctorLoading.value = false;
	}
};
// 方法：获取结算列表
const getSettlementList = async (room) => {
	try {
		// 检查必需参数
		const requiredParams = [currentCard.value, room?.id, room?.bed_num];
		const paramNames = ['就诊卡号', '房间ID', '床号'];
		const missingFields = [];

		requiredParams.forEach((param, index) => {
			if (!param) {
				missingFields.push(paramNames[index]);
			}
		});

		if (missingFields.length > 0) {
			ElMessage.error(`缺少必需参数: ${missingFields.join(', ')}`);
			settlementData.value = [];
			return;
		}

		// 打印请求参数用于调试
		console.log('结算列表请求参数:', {
			card: currentCard.value?.toString() || '',
			room_id: room.id?.toString() || '',
			bed: room.bed_num?.toString() || '',
			day: '1',
		});

		settlementLoading.value = true;
		const res = await settlementList().signIn({
			card: currentCard.value?.toString() || '',
			room_id: room.id?.toString() || '',
			bed: room.bed_num?.toString() || '',
			day: '1',
		});

		console.log('结算列表接口返回完整数据:', res); // 增加完整返回数据的日志

		if (res?.code === 1) {
			// 处理不同的数据结构
			let rawData = [];
			if (Array.isArray(res.data)) {
				console.log('数据结构: res.data 是数组');
				rawData = res.data;
			} else if (res.data && Array.isArray(res.data.data)) {
				console.log('数据结构: res.data.data 是数组');
				rawData = res.data.data;
			} else if (res.data && Array.isArray(res.data.list)) {
				console.log('数据结构: res.data.list 是数组');
				rawData = res.data.list;
			} else if (res.data && typeof res.data === 'object' && res.data !== null) {
				console.log('数据结构: res.data 是对象');
				// 如果res.data是一个对象但不是数组，尝试将其放入数组中
				rawData = [res.data];
			} else {
				console.log('数据结构: res.data 不是有效数组或对象');
				rawData = [];
			}

			console.log('处理前的原始数据:', rawData);

			// 处理并标准化数据
			settlementData.value = rawData.map((item, index) => {
				// 确保所有需要的字段都存在
				if (!item || typeof item !== 'object') {
					console.warn(`结算数据第${index}项不是有效对象:`, item);
					return {
						id: null,
						service_name: '未知服务',
						service_type: 0,
						specification: 0,
						specifi: '1盒',
						subtotal: 0,
						status: 1,
					};
				}

				const processedItem = {
					id: item.id || null,
					service_name: item.service_name || item.name || '未知服务',
					// 服务类型: 1=药品, 2=体检 (与新增服务时保持一致)
					service_type: item.service_type !== undefined ? parseInt(item.service_type) : item.type !== undefined ? parseInt(item.type) : 0,
					specification: parseFloat(item.specification) || parseFloat(item.price) || 0,
					specifi: item.specifi || item.number || item.specification || '1盒',
					subtotal: parseFloat(item.subtotal) || parseFloat(item.money) || parseFloat(item.price) || 0,
					status: item.status !== undefined ? parseInt(item.status) : 1,
				};

				console.log(`处理后的第${index}项数据:`, processedItem);
				return processedItem;
			});

			console.log('最终结算列表数据:', settlementData.value);
			console.log('结算数据长度:', settlementData.value.length);

			// 重置分页
			settlementCurrentPage.value = 1;
		} else {
			const errorMsg = res?.msg || '获取费用明细失败';
			console.error('获取费用明细失败:', errorMsg);
			ElMessage.error(errorMsg);
			settlementData.value = [];
		}
	} catch (error) {
		console.error('获取结算列表异常:', error);
		// 提供更详细的错误信息
		if (error.response) {
			// 服务器返回了错误响应
			console.error('服务器响应错误:', error.response.status, error.response.data);
			ElMessage.error(`服务器错误 ${error.response.status}: ${error.response.data?.msg || '未知错误'}`);
		} else if (error.request) {
			// 请求已发出但没有收到响应
			console.error('网络请求无响应:', error.request);
			ElMessage.error('网络请求无响应，请检查网络连接');
		} else {
			// 其他错误
			console.error('请求配置错误:', error.message);
			ElMessage.error(`请求错误: ${error.message}`);
		}
		settlementData.value = [];
	} finally {
		settlementLoading.value = false;
	}
};

// 方法：获取体检套餐列表
const getPackageList = async () => {
	try {
		packageLoading.value = true;
		const res = await checkPackage().signIn({});

		if (res.code === 1) {
			// 处理不同的数据结构
			if (Array.isArray(res.data)) {
				packageList.value = res.data;
			} else if (res.data && Array.isArray(res.data.data)) {
				packageList.value = res.data.data;
			} else if (res.data && Array.isArray(res.data.list)) {
				packageList.value = res.data.list;
			} else {
				packageList.value = [];
			}
		} else {
			console.error('获取体检套餐失败:', res.msg || '未知错误');
			packageList.value = [];
		}
	} catch (error) {
		console.error('获取体检套餐异常:', error);
		packageList.value = [];
	} finally {
		packageLoading.value = false;
	}
};
// 方法：获取药品列表
const getDrugList = async () => {
	try {
		drugLoading.value = true;
		const res = await medicineList().signIn({});

		if (res.code === 1) {
			// 处理不同的数据结构
			if (Array.isArray(res.data)) {
				drugList.value = res.data;
			} else if (res.data && Array.isArray(res.data.data)) {
				drugList.value = res.data.data;
			} else if (res.data && Array.isArray(res.data.list)) {
				drugList.value = res.data.list;
			} else {
				drugList.value = [];
			}
		} else {
			console.error('获取药品列表失败:', res.msg || '未知错误');
			drugList.value = [];
		}
	} catch (error) {
		console.error('获取药品列表异常:', error);
		drugList.value = [];
	} finally {
		drugLoading.value = false;
	}
};

// 方法：获取关系文本
const getRelationText = (status) => {
	// 根据实际业务逻辑调整
	const relationMap = {
		1: '本人',
		2: '家属',
		3: '朋友',
		4: '其他',
	};
	return relationMap[status] || '未知';
};

// 方法：获取结算患者头像
const getSettlementPatientAvatar = () => {
	if (settlementPatientInfo.value.avatar) {
		return `${BASE_IMAGE_URL}${settlementPatientInfo.value.avatar}`;
	}
	return DEFAULT_AVATAR;
};

// 方法：预览结算患者头像
const previewSettlementAvatar = () => {
	settlementAvatarPreviewVisible.value = true;
};
// 方法：获取状态标签类型
const getStatusTagType = (status) => {
	switch (status) {
		case 0:
			return 'warning';
		case 1:
			return 'success';
		case 2:
			return 'danger';
		default:
			return 'info';
	}
};

// 方法：获取结算订单状态文本（已支付/未支付）
const getSettlementStatusText = (status) => {
	// 根据data.status的值来判断就诊状态
	switch (status) {
		case 0:
			return '未支付';
		case 1:
			return '已支付';
		case 2:
			return '已退款';
		default:
			return '未知状态';
	}
};

// 方法：服务类型改变
const handleServiceTypeChange = (value) => {
	// 重置服务相关字段
	serviceForm.service_id = '';
	serviceForm.price = 0;
	serviceForm.subtotal = 0;
	serviceForm.specification = 1;

	// 根据选择的服务类型预加载数据
	if (value === '1' && packageList.value.length === 0) {
		// 体检
		getPackageList();
	} else if (value === '2' && drugList.value.length === 0) {
		// 药品
		getDrugList();
	}
};

// 方法：服务改变
const handleServiceChange = (value) => {
	if (!value) {
		serviceForm.price = 0;
		serviceForm.subtotal = 0;
		return;
	}

	// 查找选中的服务
	let selectedService = null;
	if (serviceForm.service_type === '1') {
		// 体检
		selectedService = packageList.value.find((item) => item.id == value);
	} else if (serviceForm.service_type === '2') {
		// 药品
		selectedService = drugList.value.find((item) => item.id == value);
	}

	// 设置单价并计算小计
	if (selectedService) {
		serviceForm.price = parseFloat(selectedService.price) || 0;
		calculateSubtotal();
	} else {
		serviceForm.price = 0;
		serviceForm.subtotal = 0;
	}
};

// 方法：计算小计
const calculateSubtotal = () => {
	const price = parseFloat(serviceForm.price) || 0;
	const quantity = parseInt(serviceForm.specification) || 0;
	serviceForm.subtotal = price * quantity;
};

// 监听规格变化，重新计算小计
watch(
	() => serviceForm.specification,
	() => {
		if (serviceForm.price) {
			calculateSubtotal();
		}
	}
);

// 方法：打开新增服务弹窗
const openAddServiceDialog = () => {
	// 重置表单
	Object.assign(serviceForm, {
		service_type: '',
		service_id: '',
		specification: 1,
		price: 0,
		subtotal: 0,
	});

	addServiceVisible.value = true;

	// 预加载数据
	if (packageList.value.length === 0) {
		getPackageList();
	}
	if (drugList.value.length === 0) {
		getDrugList();
	}
};

// 方法：取消新增服务
const cancelAddService = () => {
	addServiceVisible.value = false;
	// 重置表单验证
	if (serviceFormRef.value) {
		serviceFormRef.value.resetFields();
	}
};

// 方法：确认新增服务
const confirmAddService = () => {
	serviceFormRef.value.validate(async (valid) => {
		if (valid) {
			try {
				// 构造请求数据 - type使用数字类型 (体检=2, 药品=1)
				const requestData = {
					room_id: currentRoom.value.id?.toString() || '',
					name_id: serviceForm.service_id?.toString() || '',
					type: serviceForm.service_type === '2' ? 1 : 2, // 数字类型: 1=药品, 2=体检
					price: serviceForm.price?.toString() || '0', // 字符串类型
					number: serviceForm.specification || 1, // 数字类型
					money: serviceForm.subtotal || 0, // 小计使用money字段，数字类型
					status: 2, // 数字类型
					img: '', // 字符串类型
					day: 1, // 数字类型
					bed: parseInt(currentRoom.value.bed_num) || 0, // 数字类型
					card: currentCard.value?.toString() || '', // 字符串类型
				};

				console.log('发送的请求数据:', requestData); // 调试信息

				const res = await settlementAdd().signIn(requestData);

				if (res.code === 1) {
					ElMessage.success('新增服务成功');
					addServiceVisible.value = false;
					// 重新获取结算列表
					getSettlementList(currentRoom.value);
				} else {
					ElMessage.error(res.msg || '新增服务失败');
				}
			} catch (error) {
				console.error('新增服务异常:', error);
				ElMessage.error('新增服务失败，请重试');
			}
		}
	});
};

// 方法：处理删除
const handleDelete = async (id, index) => {
	ElMessageBox.confirm('确定要删除这条记录吗？', '确认删除', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				// 使用专门的删除接口而不是通用request
				const res = await settlementDelete().signIn({ id });

				if (res.code === 1) {
					ElMessage.success('删除成功');
					// 重新获取结算列表
					getSettlementList(currentRoom.value);
				} else {
					ElMessage.error(res.msg || '删除失败');
				}
			} catch (error) {
				console.error('删除记录异常:', error);
				ElMessage.error('删除失败，请重试');
			}
		})
		.catch(() => {
			// 取消删除
		});
};

// 方法：处理有体检项目的就诊完成
const handleCompleteWithExam = () => {
	showCompleteOptions.value = false;
	// 重置体检表单
	Object.assign(examForm, {
		name: '',
		result: '',
		file: null,
	});
	examFileList.value = [];
	uploadExamVisible.value = true;
};

// 方法：处理没有体检项目的就诊完成
const handleCompleteWithoutExam = async () => {
	showCompleteOptions.value = false;

	// 添加二次确认框
	ElMessageBox.confirm(
		'确定要完成就诊并办理出院吗？此操作不可撤销。',
		'确认就诊完成',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}
	)
	.then(async () => {
		try {
			// 准备出院请求参数
			const requestData = {
				details: '血常规的介绍',
				room_num: currentRoom.value.room_num?.toString() || '',
				bed_num: currentRoom.value.bed_num?.toString() || '',
				card: currentCard.value?.toString() || '',
			};

			const res = await outHospital().signIn(requestData);

			if (res.code === 1) {
				ElMessage.success('就诊完成，已成功出院');
				// 返回房间列表
				goBack();
				// 刷新房间列表
				await getRoomList();
			} else {
				ElMessage.error(res.msg || '处理失败');
			}
		} catch (error) {
			console.error('就诊完成异常:', error);
			ElMessage.error('处理失败，请重试');
		}
	})
	.catch(() => {
		// 用户取消操作
		ElMessage.info('已取消操作');
	});
};

// 方法：处理体检文件上传 - 优化版本
const handleExamFileChange = (file, fileList) => {
	// 检查文件数量限制
	if (fileList.length > 1) {
		ElMessage.error('只能上传一个文件');
		// 保留第一个文件，移除多余的
		examFileList.value = fileList.slice(0, 1);
		examForm.file = examFileList.value[0]?.raw || null;
		return;
	}

	// 检查文件大小
	if (file.raw.size > maxFileSize.value) {
		ElMessage.error(`文件大小不能超过${maxFileSize.value / 1024 / 1024}MB`);
		examFileList.value = [];
		examForm.file = null;
		return;
	}

	// 检查文件类型
	const validTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif'];
	if (!validTypes.includes(file.raw.type)) {
		ElMessage.error('只支持 PDF、JPG、PNG、GIF 格式的文件');
		examFileList.value = [];
		examForm.file = null;
		return;
	}

	examFileList.value = [file];
	examForm.file = file.raw;

	// 清除表单验证错误
	if (examFormRef.value) {
		examFormRef.value.clearValidate('file');
	}
};

// 方法：移除体检文件
const handleExamFileRemove = (file, fileList) => {
	examFileList.value = fileList;
	examForm.file = fileList.length > 0 ? fileList[0].raw : null;

	// 如果文件被删除，重新验证字段
	if (examFormRef.value) {
		examFormRef.value.validateField('file');
	}
};

// 方法：取消上传体检报告
const cancelUploadExam = () => {
	uploadExamVisible.value = false;
	// 重置表单验证
	if (examFormRef.value) {
		examFormRef.value.resetFields();
	}
};

// 方法：确认上传体检报告 - 优化版本
const confirmUploadExam = () => {
	examFormRef.value.validate(async (valid) => {
		if (valid) {
			// 添加二次确认框
			ElMessageBox.confirm(
				'确定要上传体检报告并完成就诊吗？此操作不可撤销。',
				'确认就诊完成',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(async () => {
				// 显示上传中状态
				const loading = ElMessage({
					message: '正在上传体检报告...',
					type: 'info',
					duration: 0,
				});

				try {
					// 先上传体检报告文件
					let fileUrl = '';
					if (examForm.file) {
						const fileFormData = new FormData();
						fileFormData.append('file', examForm.file);

						const fileRes = await upload().signIn(fileFormData);
						if (fileRes.code === 1) {
							fileUrl = fileRes.data.url || '';
						} else {
							// 关闭加载提示
							loading.close();
							ElMessage.error(fileRes.msg || '文件上传失败');
							return;
						}
					}

					// 准备包含体检数据的出院请求参数
					const requestData = {
						details: '血常规的介绍',
						room_num: currentRoom.value.room_num?.toString() || '',
						bed_num: currentRoom.value.bed_num?.toString() || '',
						card: currentCard.value?.toString() || '',
						exam_name: examForm.name,
						exam_result: examForm.result,
						has_exam: '1',
					};

					// 如果有文件上传成功，添加文件URL
					if (fileUrl) {
						requestData.file = fileUrl;
					}

					const res = await outHospital().signIn(requestData);

					// 关闭加载提示
					loading.close();

					if (res.code === 1) {
						ElMessage.success('体检报告上传成功，就诊已完成');
						uploadExamVisible.value = false;
						// 重置表单
						Object.assign(examForm, {
							name: '',
							result: '',
							file: null,
						});
						examFileList.value = [];
						// 返回房间列表
						goBack();
						// 刷新房间列表
						await getRoomList();
					} else {
						// 处理服务器返回的错误
						ElMessage.error(res.msg || '上传失败');
					}
				} catch (error) {
					// 关闭加载提示
					loading.close();
					console.error('上传体检报告异常:', error);

					// 提供更详细的错误信息
					if (error.message && error.message.includes('Network Error')) {
						ElMessage.error('网络错误，请检查网络连接');
					} else if (error.response && error.response.status === 413) {
						ElMessage.error('文件过大，请选择较小的文件');
					} else {
						ElMessage.error('上传失败，请重试');
					}
				}
			})
			.catch(() => {
				// 用户取消操作
				ElMessage.info('已取消操作');
			});
		}
	});
};

// 获取就诊卡信息
const getCardInfo = async (cardId) => {
	try {
		const res = await cardList().signIn({ card: cardId });
		if (res.code === 1) {
			// 处理不同的数据结构
			if (Array.isArray(res.data) && res.data.length > 0) {
				patientCardInfo.value = res.data[0];
			} else if (res.data && typeof res.data === 'object') {
				patientCardInfo.value = res.data;
			} else {
				patientCardInfo.value = res.data || {};
			}
		} else {
			ElMessage.error(res.msg || '获取就诊卡信息失败');
			patientCardInfo.value = {};
		}
	} catch (error) {
		console.error('获取就诊卡信息异常:', error);
		ElMessage.error('获取就诊卡信息失败，请重试');
		patientCardInfo.value = {};
	}
};

// 页面加载时获取科室列表和房间列表
onMounted(() => {
	getDepartmentList();
	getRoomList();
});
</script>

<style scoped>
/* 基础样式 */
.addRoom_box {
	width: 100%;
	height: 60px;
	background-color: #f3f8ff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30px;
}

.view-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
	margin-left: 20px;
}

/* 房间部分 */
.room_box {
	width: 96%;
	min-height: 80vh;
	margin-left: 2%;
	border-radius: 5px;
	background: #fff;

	> .room_title {
		width: 100%;
		height: 50px;
		font-weight: 700;
		font-size: 23px;
		line-height: 50px;
		background-color: #fff;
		display: flex;
		justify-content: flex-start;
		padding-left: 20px;
	}
}

.room_search {
	display: flex;
	align-items: center;
	padding: 10px 0;
	flex-wrap: wrap;
}

/* 房间列表样式优化 */
.room_list {
	padding: 8px;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 8px;
	max-width: 100%;
}

.room_list_item_wrapper {
	display: flex;
	align-items: center;
	padding: 8px;
	border: 1px solid #ebeef5;
	border-radius: 3px;
	box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
	transition: box-shadow 0.1s ease;
	min-height: 90px;
}

.room_list_item_wrapper:hover {
	box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.15);
}

/* 图片区域 */
.room_list_item {
	flex: 0 0 70px;
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 8px;
	overflow: hidden;
}

/* 房间信息区域 */
.room_list_itemText {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	margin: 0 6px;
}

.room_list_item_info {
	display: flex;
	align-items: center;
	margin-bottom: 2px;
}

.item_roomNum {
	font-size: 11px;
	font-weight: bold;
	margin-right: 8px;
}

.room_list_item_info_office {
	font-size: 10px;
	margin-right: 8px;
	color: #606266;
}

.room_list_item_bedNum {
	font-size: 11px;
	color: #909399;
}

.room_list_item_state {
	margin-bottom: 2px;
}

.room_list_item_state_text {
	font-size: 11px;
	font-weight: bold;
}

.status-free {
	color: #67c23a;
}

.status-occupied {
	color: #f56c6c;
}

.room_list_item_time_text {
	font-size: 10px;
	color: #409eff;
}

/* 功能按钮区域 */
.room_list_item_function {
	flex: 0 0 50px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	gap: 4px;
}

.room_list_item_function .el-button {
	width: 48px;
	padding: 5px 6px;
	font-size: 11px;
	border-radius: 2px;
	margin-left: auto;
}

/* 分页容器 */
.pagination-container {
	display: flex;
	justify-content: center;
	padding: 20px 0;
}

/* 查房页面样式 */
.check-room-container {
	width: 96%;
	margin: 0 auto;
	background: #fff;
	border-radius: 5px;
	padding: 15px;
	min-height: 80vh;
}

.check-header {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
}

.back-button {
	margin-right: 15px;
}

.check-title {
	font-size: 20px;
	font-weight: bold;
}

/* 患者信息 - 头像在右侧 */
.patient-info {
	display: flex;
	justify-content: space-between;
	margin-bottom: 25px;
	padding: 15px;
	background-color: #f9f9f9;
	border-radius: 5px;
	align-items: flex-start;
}

.patient-details {
	flex: 1;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 12px 20px;
}

.patient-avatar {
	/* display: flex; */
	flex-direction: column;
	align-items: center;
	margin-left: 20px;
	min-width: 100px;
}

.patient-avatar .el-image {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	cursor: pointer;
}

.preview-text {
	margin-top: 8px;
	font-size: 12px;
	color: #666;
}

.image-error {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f5f7fa;
	color: #909399;
}

.image-error .el-icon {
	font-size: 24px;
}

.patient-avatar .el-image {
	cursor: pointer;
}

.detail-item {
	font-size: 14px;
}

.detail-item .label {
	font-weight: bold;
	color: #333;
}

/* 查房记录区域 */
.check-record {
	display: flex;
	gap: 20px;
	min-height: 400px;
}

.timeline-container {
	/* flex: 0 0 10px; */
	border-right: 1px solid #eee;
	padding-right: 15px;
	max-height: 500px;
	overflow-y: auto;
}

.timeline-content {
	font-size: 14px;
	cursor: pointer;
}

.active-timeline {
	.el-timeline-item__node {
		background-color: #409eff;
	}

	.timeline-content {
		color: #409eff;
		font-weight: bold;
	}
}

.check-form {
	flex: 1;
	padding: 0 15px;
}

/* 表单新布局样式 */
.form-row {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 16px;
	align-items: center;
}

.form-group {
	display: flex;
	align-items: center;
	margin-right: 24px;
	margin-bottom: 8px;
}

.form-group.full-width {
	flex: 1;
	margin-right: 0;
}

.form-label {
	font-weight: 500;
	margin-right: 8px;
	min-width: 100px;
	text-align: right;
}

.form-value {
	color: #606266;
}

/* 表单验证错误提示样式 */
.el-form-item {
	margin-bottom: 18px;
}

.el-form-item__error {
	color: #f56c6c;
	font-size: 12px;
	line-height: 1;
	padding-top: 4px;
	position: absolute;
	top: 100%;
	left: 0;
}

.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-textarea__inner {
	border-color: #f56c6c;
}

.form-group .el-form-item {
	margin-bottom: 0;
	width: 100%;
}

.check-buttons {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
	margin-top: 30px;
	padding-top: 15px;
	border-top: 1px solid #eee;
}

.preview-avatar {
	width: 100%;
	height: auto;
	border-radius: 5px;
}

/* 结算页面样式 - 新增 */
.settlement-container {
	width: 100%;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.settlement-content {
	width: 96%;
	margin: 20px auto;
	background: #fff;
	border-radius: 5px;
	padding: 15px;
}

.settlement-actions {
	display: flex;
	justify-content: space-between;
	margin-bottom: 15px;
	padding: 10px;
	background-color: #f9f9f9;
	border-radius: 4px;
}

.settlement-table {
	margin-bottom: 20px;
}

.no-records {
	text-align: center;
	padding: 40px 0;
	color: #999;
	font-size: 14px;
}

.complete-options {
	padding: 10px 0;
}

.option-item {
	padding: 8px 16px;
	cursor: pointer;
	transition: background-color 0.2s;
}

.option-item:hover {
	background-color: #f5f5f5;
}

/* 文件信息样式 */
.file-info {
	margin-top: 8px;
	font-size: 12px;
	color: #606266;
}

.file-limit {
	color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 1600px) {
	/* .room_list { */
	/* grid-template-columns: repeat(3, 1fr); */
	/* } */

	.patient-details {
		grid-template-columns: repeat(3, 1fr);
	}
}

@media (max-width: 1200px) {
	.room_list {
		grid-template-columns: repeat(2, 1fr);
	}

	.patient-details {
		grid-template-columns: repeat(2, 1fr);
	}

	.check-record {
		flex-direction: column;
	}

	.timeline-container {
		flex: none;
		border-right: none;
		border-bottom: 1px solid #eee;
		padding-right: 0;
		padding-bottom: 15px;
		max-height: 250px;
	}

	.form-group {
		flex: 1 0 40%;
	}
}

@media (max-width: 768px) {
	.room_list {
		grid-template-columns: 1fr;
	}

	.room_search {
		flex-direction: column;
		align-items: flex-start;
	}

	.room_search > * {
		margin-left: 0 !important;
		margin-top: 6px;
		width: 100% !important;
	}

	.patient-info {
		flex-direction: column;
		align-items: flex-start;
	}

	.patient-avatar {
		margin-left: 0;
		margin-top: 15px;
		align-self: center;
	}

	.patient-details {
		grid-template-columns: 1fr;
		width: 100%;
	}

	.form-row {
		flex-direction: column;
		align-items: flex-start;
	}

	.form-group {
		width: 100%;
		margin-right: 0;
	}

	.form-label {
		text-align: left;
	}

	.settlement-actions {
		flex-direction: column;
		gap: 10px;
	}

	.settlement-actions .el-button {
		width: 100%;
	}
}

.check-room-container {
	width: 96%;
	margin: 0 auto;
	background: #fff;
	border-radius: 5px;
	padding: 15px;
	min-height: 80vh;
}

.no-records {
	text-align: center;
	padding: 20px;
	color: #999;
}

.check-header {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
}

.detail-row {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 8px;
}

.patient-avatar-small {
	width: 50px;
	height: 50px;
	border-radius: 50%;
	cursor: pointer;
}

.avatar-item {
	display: flex;
	align-items: center;
}
</style>
